//
//  Iapppay.m
//  夺宝吧
//
//  Created by weienjie on 15/9/18.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "Iapppay.h"
#import "NSString+UrlEncode.h"
#import "PayedVC.h"


//回调地址
#define DEL_ORDER_URL @"/api/ApiPay/cancelCartOrdersForPay"
#define DEL_CHONGZHI_URL @"/api/ApiPay/cancelRechargeOrdersForPay"

@interface Iapppay() <IapppayKitPayRetDelegate>
{
    //记录订单编号
    NSString *_orderId;
}
@end


@implementation Iapppay

- (instancetype)initWithPayModel:(PayInfoModel *)payModel{
    if (self = [self init]){
        self.payModel = payModel;
        
        self.mOrderUtilsAppId  = self.payModel.appid;
        self.mOrderAppUserId = self.payModel.seller;
        
        //公钥 私钥
        self.mOrderUtilsCheckResultKey = self.payModel.public_key;
        self.mOrderUtilsCpPrivateKey   = self.payModel.private_key;
        
        return self;
    }
    
    return nil;
}


//爱贝支付接口
- (void)iappayWithOrderId:(NSString *)orderId price:(NSString *)pirce privateInfo:(NSString *)info wareName:(NSString*)waresName
{
    IapppayOrderUtils *orderInfo = [[IapppayOrderUtils alloc] init];
    orderInfo.appId         = self.mOrderUtilsAppId;
    orderInfo.appUserId     = self.mOrderAppUserId;
    orderInfo.cpPrivateKey  = self.mOrderUtilsCpPrivateKey;
    orderInfo.notifyUrl     = mOrderUtilsNotifyurl;
    orderInfo.waresId       = mOrderWaresId;
    orderInfo.waresName     = waresName;
    
    if (!orderId || !pirce) {
        return;
    }
    _orderId = orderId;
    orderInfo.cpOrderId     = orderId;
    orderInfo.price         = pirce;
    orderInfo.cpPrivateInfo = info;
    
    NSString *trandInfo = [orderInfo getTrandData];
    
    [[IapppayKit sharedInstance] makePayForTrandInfo:trandInfo payDelegate:self];


}

/**
 * 此处方法是支付结果处理
 **/
#pragma mark - IapppayKitPayRetDelegate
- (void)iapppayKitRetPayStatusCode:(IapppayKitPayRetCodeType)statusCode
                        resultInfo:(NSDictionary *)resultInfo
{
    NSLog(@"statusCode : %d, resultInfo : %@", (int)statusCode, resultInfo);
    
    if (statusCode == IAPPPAY_PAYRETCODE_SUCCESS)
    {
        NSString *signature = resultInfo[@"Signature"];
        NSString *signatureText = [signature urlDecode];
        
        BOOL isSuccess = [IapppayOrderUtils checkPayResult:signatureText withAppKey:self.mOrderUtilsCheckResultKey];
        if (isSuccess) {
            //支付成功，验签成功,直接照搬支付宝成功提示
            if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
                //跳往支付结果界面刷新结果
                PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
                if(self.isChongZhiFlag){
                    payedVC.rltType = ChongZhiSuccess;
                }else{
                    payedVC.rltType = PdcSuccess;
                }
                [payedVC updateViews];
            }
            return;
        }
    }
    else
    {
        //支付取消
        NSString *message = @"支付取消";
        if (resultInfo != nil) {
            message = [NSString stringWithFormat:@"%@:code:%@\n（%@）",message,resultInfo[@"RetCode"],resultInfo[@"ErrorMsg"]];
        }
        //取消订单
        if (self.isChongZhiFlag) {
            [self cancelChangzhiOrder];
        }else{
            [self cancelOrder];
        }
        //跳往支付结果界面
        if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
            //跳往支付结果界面刷新结果
            PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
            if(self.isChongZhiFlag){
                payedVC.rltType = ChongZhiFailed;
            }else{
                payedVC.rltType = PdcFailed;
            }
            [payedVC updateViews];
        }
    }
}
//照搬支付宝支付流程

//取消订单
-(void)cancelOrder
{
    //取消订单
    NSDictionary *params = @{@"ids":_orderId,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DEL_ORDER_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        //        NSLog(@"取消订单成功！");
    } failedBlock:^{
    } needLog:NO];
    
}
//取消充值订单
- (void)cancelChangzhiOrder
{
    //取消订单
    NSDictionary *params = @{@"ids":_orderId,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DEL_CHONGZHI_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        //        NSLog(@"取消订单成功！");
    } failedBlock:^{
    } needLog:NO];
}

@end
